package com.opensso.sdk.client;

import com.alibaba.fastjson.JSON;
import com.opensso.sdk.security.OkhttpLogInterceptor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 访问sso服务器的封装
 * Created by lixin on 2018/8/6.
 */
@Slf4j
public class SSORequest {


    /**
     * post 方式请求后端接口
     *
     * @param url    api 地址
     * @param token  登录的token进行验证
     * @param apiKey 授权apikey
     * @return SSOResponse
     */
    public SSOResponse authorizationPost(String url, String token, String apiKey) {
        return this.post(url, token, apiKey, SessionEnum.Authorization);
    }


    /**
     * post 方式请求后端接口
     *
     * @param url    api 地址
     * @param token  登录的token进行验证
     * @param apiKey 授权apikey
     * @return SSOResponse
     */
    public SSOResponse refreshPost(String url, String token, String apiKey) {
        return this.post(url, token, apiKey, SessionEnum.RefreshToken);
    }


    /**
     * post 方式请求后端接口
     *
     * @param url    api 地址
     * @param token  登录的token进行验证
     * @param apiKey 授权apikey
     * @return SSOResponse
     */
    public SSOResponse post(String url, String token, String apiKey, SessionEnum sessionEnum) {
        RequestBody formBody = new FormBody.Builder()
                //required
                .add(SessionEnum.ApiKey.name(), apiKey)
                //required
                .add(SessionEnum.Token.name(), token)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .addHeader("accept", "application/json")
                .addHeader(sessionEnum.name(), token)
                .addHeader(SessionEnum.ApiKey.name(), apiKey)
                .build();
        return this.http(request);
    }


    /**
     * okhttp的网络请求
     *
     * @param request 请求对象
     * @return SSOResponse
     */
    private SSOResponse http(Request request) {
        OkHttpClient client = new OkHttpClient.Builder().writeTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS).connectTimeout(15, TimeUnit.SECONDS)
                .addInterceptor(new OkhttpLogInterceptor()).build();
        Response response = null;
        SSOResponse ssoResponse = null;
        try {
            log.info(request.toString());
            response = client.newCall(request).execute();
            String jsonResult = response.body().string();
            log.info("SSOResponse << " + jsonResult);
            ssoResponse = JSON.parseObject(jsonResult, SSOResponse.class);
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.toString());
            ssoResponse = new SSOResponse(false);
        }
        return ssoResponse;
    }
}
